import { baseUrl } from './api.js'

//获取openid
function getOpenid() {
	return new Promise((resolve, reject) => {
		//地址
		const url = baseUrl+'/d/user/getOpenid'
		//1.获取code
		uni.login({
			provider:'weixin',
			success:res=>{
				//2.根据code获取openid
				uni.request({
					url: url,  
					method:'GET',  
					data: {  
						code: res.code,                    
						grant_type: 'authorization_code',
					},  
					success: (cts) => {
						if(cts.data.code == 1){
							//缓存openid
							uni.setStorageSync('openid', cts.data.data.openid)
							resolve(cts.data.data.openid)
						}else{
							uni.showModal({
								title: '提示',
								content: 'openid获取失败',
								showCancel: false,
								confirmColor: '#2979FF'
							})
							reject()
						} 
					},
					fail() {
						uni.showModal({
							title: '提示',
							content: '网络错误请重试',
							showCancel: false,
							confirmColor: '#2979FF'
						})
						reject()
					}
				}); 
			},
				
		})
	})
}

//登录
function login(mobile) {
	return new Promise((resolve, reject) => {
		//地址
		const url = baseUrl+'/user/mobilelogin2'
		const openid = uni.getStorageSync('openid')
		const pid  = uni.getStorageSync('pid')
		if(!openid){
			uni.showToast({
				icon:"none",
				title:"openid不能为空"
			})
			return 
		}
		uni.request({
			url: url,  
			method:'POST',  
			data: {  
				pid: pid??0,
				openid: openid,
				mobile: mobile
			},  
			success: (cts) => {
				if(cts.data.code == 1){
					//缓存token
					uni.setStorageSync('token',cts.data.data.userinfo.token)
					//缓存用户信息
					uni.setStorageSync('user',cts.data.data.userinfo)
					resolve()
				}else{
					uni.showToast({
						icon:"none",
						title:"授权失败"
					})
					reject()
				} 
			},
			fail() {
				reject()
			}
		}); 
	})
}

export default {
	getOpenid,
	login,
}